package com.example.hrmsaas.system.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Getter;
import lombok.Setter;


import java.util.Date;
import java.util.Map;

@Getter
@Setter

public class JwtUtils {
    //解析token串的盐（签名私钥）
    private String salt;

    //签名失效时间
    private Long stopTime = 3600000L;

    /**
     *  设置签名token
     * @param id  登录姓名
     * @param name 名称
     * @param salt 签名秘钥
     * @param map  自定义参数
     * @return token
     */
    public String createJwt(String id, String name, String salt, Map<String,Object> map){
        this.salt = salt;
        Long now  = System.currentTimeMillis();
        long endTime = now + this.stopTime;
        JwtBuilder jwtBuilder = Jwts.builder().setId(id).setSubject(name)
                .setIssuedAt(new Date()).signWith(SignatureAlgorithm.HS256,this.salt);
        //jwtBuilder.setClaims(map);
        for(Map.Entry<String,Object> entry:map.entrySet()){
            jwtBuilder.claim(entry.getKey(),entry.getValue());
        }
        jwtBuilder.setExpiration(new Date(endTime));
        return jwtBuilder.compact();
    }
    /***
     * 设置解析签名token
     */
    public Claims analysisJwt(String token, String salt){
        this.salt = salt;
        return Jwts.parser().setSigningKey(this.salt).parseClaimsJws(token).getBody();
    }
}
